#include "HaffmanDecoder.h"

void HaffmanDecoder::engine(IDataReader* reader,IDataWriter* writer,TreeReader* treeReader)
{
	INode* root = treeReader->read(reader);
	INode* tree = root;
	int count = 0;
	char byte = reader->getChar();
	while(!reader->isEnd())
	{
		bool b = byte & (1 << (7 - count));
		++count;
		if(b)
			tree = tree->right();
		else
			tree = tree->left();
		if(NULL == tree)
			continue;
		if((NULL == tree->left()) && (NULL == tree->right()))
		{
			char c = tree->getChar();
			writer->putChar(c);
			tree = root;
		}
		if(8 == count)
		{
			count = 0;
			byte = reader->getChar();
		}
	}
}

void HaffmanDecoder::start(char* toRead,char* toWrite)
{
	engine(&TextReader(toRead),&TextWriter(toWrite), &TreeReader());
}